package dao.impl;

import dao.ISystemManagementDao;
import pojo.Employees;
import pojo.Users;
import util.DBHelper;

import java.util.ArrayList;

public class SystemManagementDao implements ISystemManagementDao {
    private DBHelper db = new DBHelper();

    //系统管理
    //用户信息列表查看(动态模糊查询,初始状态为无条件全查)
    // 在SystemManagementDao.selectUsers中：
    @Override
    public ArrayList<Users> selectUsers(Users users) {
        StringBuilder sql = new StringBuilder("select * from users where 1=1");
        // 改为使用数组而不是ArrayList
        ArrayList<Object> paramList = new ArrayList<>();

        if (users.getUsername() != null) {
            sql.append(" and username like ?");
            paramList.add("%" + users.getUsername() + "%");
        }

        // 将ArrayList转换为数组
        Object[] params = paramList.toArray();
        return db.dtQuery(sql.toString(), Users.class, params);
    }

    //根据姓名从users表和employees表中查出users的eId;
    @Override
    public ArrayList<Users> selectEidByName(String username) {
        String sql = "select e.* from employees e,users u where e.eName=u.username and u.username=?";
        return db.dtQuery(sql, Employees.class, username);
    }

    //用户添加(参数为用户对象)
    @Override
    public int insertUser(Users users) {
        String sql = "insert into users values(null,?,?,?,?,?,?)";
        Object[] obj = {users.getUsername(),
                users.getPassword(),
                users.getRole(),
                users.getuCreatedAt(),
                users.getuUpdatedAt(),
                users.geteId()};
        return db.dtUpdate(sql, obj);
    }

    //当前用用户信息修改(根据用户ID修改)
    @Override
    public int updateUser(Users users) {
        String sql = "update users set username=?," +
                "password=?," +
                "uUpdatedAt=?";
        Object[] obj = {users.getUsername(),
                users.getPassword(),
                users.getuUpdatedAt()};
        return db.dtUpdate(sql, obj);
    }

    //用户详细信息查看(根据用户ID查看)
    @Override
    public ArrayList<Users> selectUser(Integer uId) {
        String sql = "select * from users where uId=?";
        return db.dtQuery(sql, Users.class, uId);
    }

    //用户信息删除(根据用户ID删除)
    @Override
    public int delUser(Integer uId) {
        String sql = "delete from users where uId=?";
        return db.dtUpdate(sql, uId);
    }
}
